import fs from 'fs';
import path from 'path';
import https from 'https';
import http from 'http';
import { fileURLToPath } from 'url';

// 获取当前文件的目录路径
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 创建保存图片的目录
const imagesDir = path.join(__dirname, 'public', 'images');
if (!fs.existsSync(imagesDir)) {
  fs.mkdirSync(imagesDir, { recursive: true });
}

// 需要下载的URL列表（仅限资源文件）
const urls = [
  'https://os.alipayobjects.com/rmsportal/mlcYmsRilwraoAe.svg',
  'https://gw.alipayobjects.com/zos/rmsportal/ruHbkzzMKShUpDYMEmHM.svg',
  'https://gw.alipayobjects.com/zos/basement_prod/b30cdc2a-d91c-4c78-be9c-7c63b308d4b3.svg',
  'https://zos.alipayobjects.com/rmsportal/HqnZZjBjWRbjyMr.png',
  'https://gw.alipayobjects.com/mdn/rms/afts/img/A*k3InRLiZDk4AAAAAAAAAAABjARQnAQ',
  'https://gw.alipayobjects.com/mdn/rms_ae7ad9/afts/img/A*-wAhRYnWQscAAAAAAAAAAABkARQnAQ',
  'https://os.alipayobjects.com/rmsportal/EejaUGsyExkXyXr.mp4',
  'https://zos.alipayobjects.com/rmsportal/HZgzhugQZkqUwBVeNyfz.jpg',
  'https://t.alipayobjects.com/images/rmsweb/T11aVgXc4eXXXXXXXX.svg',
  'https://zos.alipayobjects.com/rmsportal/faKjZtrmIbwJvVR.svg',
  'https://gw.alipayobjects.com/zos/rmsportal/PiqyziYmvbgAudYfhuBr.svg',
  'https://gw.alipayobjects.com/zos/rmsportal/SlFgHDtOTLzccvFrQHLg.png',
  'https://gw.alipayobjects.com/zos/rmsportal/qJnGrvjXPxdKETlVSrbe.svg',
  'https://gw.alipayobjects.com/zos/rmsportal/QviGtUPvTFxdhsTUAacr.svg',
  'https://gw.alipayobjects.com/zos/rmsportal/agOOBdKEIJlQhfeYhHJc.svg',
  'https://gw.alipayobjects.com/zos/rmsportal/hkLGkrlCEkGZeMQlnEkD.svg',
  'https://gw.alipayobjects.com/zos/rmsportal/bqyPRSZmhvrsfJrBvASi.svg',
  'https://gw.alipayobjects.com/zos/rmsportal/UcsyszzOabdCYDkoPPnM.svg',
  'https://gw.alipayobjects.com/zos/rmsportal/kRBeaICGexAmVjqBEqgw.svg',
  'https://gw.alipayobjects.com/zos/rmsportal/ftBIiyJcCHpHEioRvPsV.svg',
  'https://gw.alipayobjects.com/zos/rmsportal/zIUVomgdcKEKcnnQdOzw.svg',
  'https://gw.alipayobjects.com/zos/rmsportal/WIePwurYppfVvDNASZRN.svg',
  'https://zos.alipayobjects.com/rmsportal/nLzbeGQLPyBJoli.png',
  'https://zos.alipayobjects.com/rmsportal/tvQTfCupGUFKSfQ.png',
  'https://zos.alipayobjects.com/rmsportal/WBnVOjtIlGWbzyQivuyq.png',
  'https://zos.alipayobjects.com/rmsportal/YPMsLQuCEXtuEkmXTTdk.png',
  'https://zos.alipayobjects.com/rmsportal/EkXWVvAaFJKCzhMmQYiX.png',
  'https://gw.alipayobjects.com/zos/basement_prod/e339fc34-b022-4cde-9607-675ca9e05231.svg',
  'https://zos.alipayobjects.com/rmsportal/ScHBSdwpTkAHZkJ.png',
  'https://zos.alipayobjects.com/rmsportal/NKBELAOuuKbofDD.png',
  'https://zos.alipayobjects.com/rmsportal/xMSBjgxBhKfyMWX.png',
  'https://zos.alipayobjects.com/rmsportal/MNdlBNhmDBLuzqp.png',
  'https://zos.alipayobjects.com/rmsportal/UsUmoBRyLvkIQeO.png',
  'https://zos.alipayobjects.com/rmsportal/ipwaQLBLflRfUrg.png',
  'https://zos.alipayobjects.com/rmsportal/VHGOVdYyBwuyqCx.png',
  'https://zos.alipayobjects.com/rmsportal/xBrUaDROgtFBRRL.png',
  'https://gw.alipayobjects.com/zos/basement_prod/167bee48-fbc0-436a-ba9e-c116b4044293.svg',
  'https://gw.alipayobjects.com/zos/basement_prod/d8933673-1463-438a-ac43-1a8f193ebf34.svg',
  'https://gw.alipayobjects.com/mdn/rms_ae7ad9/afts/img/A*OnyWT4Nsxy0AAAAAAAAAAABjARQnAQ',
  'https://gw.alipayobjects.com/zos/basement_prod/14ce3060-34e6-4b30-9a45-1a6b95542310.svg',
  'https://gw.alipayobjects.com/mdn/rms_ae7ad9/afts/img/A*njqxS5Ky7CQAAAAAAAAAAABjARQnAQ',
  'https://gw.alipayobjects.com/mdn/rms_ae7ad9/afts/img/A*--rVR4hclJYAAAAAAAAAAABjARQnAQ',
  'https://zos.alipayobjects.com/rmsportal/qqaimmXZVSwAhpL.svg',
  'https://gw.alipayobjects.com/zos/rmsportal/NuuAwJBxewWglRSoNjET.png',
  'https://gw.alipayobjects.com/zos/rmsportal/fgGmQUfiUfSBfvsQpfOj.svg',
  'https://zos.alipayobjects.com/rmsportal/gGlUMYGEIvjDOOw.jpg',
  'https://gw.alipayobjects.com/os/s/prod/seeconf/c66ebea962cdf544926ca5a472dea5ea.jpg',
  'https://zos.alipayobjects.com/rmsportal/hzPBTkqtFpLlWCi.jpg',
  'https://zos.alipayobjects.com/rmsportal/xHxWkcvaIcuAdQl.jpg',
  'https://zos.alipayobjects.com/rmsportal/bXNBIyzSLHaycUGDzwLG.jpg',
  'https://gw.alipayobjects.com/zos/rmsportal/xTPkCNNLOnTEbGgVZOpE.jpg',
  'https://gw.alipayobjects.com/zos/rmsportal/ZsWYzLOItgeaWDSsXdZd.svg',
  'https://gw.alipayobjects.com/zos/rmsportal/TFicUVisNHTOEeMYXuQF.svg',
  'https://gw.alipayobjects.com/mdn/rms_ae7ad9/afts/img/A*fMOFSpRXMxsAAAAAAAAAAABkARQnAQ'
];

// 不应下载的URL列表（如网站链接）
const excludeUrls = [
  'https://gaode.com/place/B0FFH3KPBX',
  'https://motion.ant.design',
  'https://vite.dev',
  'https://react.dev',
  'https://landing.ant.design/docs/use/umi',
  'https://landing.ant.design/docs/use/getting-started'
];

// URL到本地路径的映射
const urlToPathMap = {};

// 下载文件的函数
function downloadFile(url, filePath) {
  return new Promise((resolve, reject) => {
    const protocol = url.startsWith('https') ? https : http;
    const file = fs.createWriteStream(filePath);
    
    const request = protocol.get(url, (response) => {
      if (response.statusCode === 200) {
        response.pipe(file);
        file.on('finish', () => {
          file.close();
          console.log(`Downloaded: ${url} -> ${filePath}`);
          resolve(filePath);
        });
      } else {
        fs.unlink(filePath, () => {}); // 删除空文件
        reject(new Error(`Failed to download ${url}: ${response.statusCode}`));
      }
    });
    
    request.on('error', (err) => {
      fs.unlink(filePath, () => {}); // 删除空文件
      reject(err);
    });
  });
}

// 生成文件名
function generateFileName(url) {
  // 从URL获取文件名
  const urlObj = new URL(url);
  let fileName = path.basename(urlObj.pathname);
  
  // 移除文件名中的特殊字符
  fileName = fileName.replace(/[<>:"/\\|?*\x00-\x1F]/g, '_');
  
  // 如果没有扩展名，根据内容类型添加扩展名
  if (!path.extname(fileName)) {
    // 简单的根据URL内容判断扩展名
    if (url.includes('svg')) {
      fileName += '.svg';
    } else if (url.includes('png')) {
      fileName += '.png';
    } else if (url.includes('jpg') || url.includes('jpeg')) {
      fileName += '.jpg';
    } else if (url.includes('mp4')) {
      fileName += '.mp4';
    } else {
      fileName += '.png'; // 默认扩展名
    }
  }
  
  // 限制文件名长度
  if (fileName.length > 100) {
    const ext = path.extname(fileName);
    fileName = fileName.substring(0, 100 - ext.length) + ext;
  }
  
  return fileName;
}

// 处理所有URL
async function processUrls() {
  console.log(`开始下载 ${urls.length} 个资源...`);
  
  // 下载所有资源文件
  for (let i = 0; i < urls.length; i++) {
    const url = urls[i];
    try {
      const fileName = generateFileName(url);
      const filePath = path.join(imagesDir, fileName);
      
      // 检查文件是否已存在
      if (fs.existsSync(filePath)) {
        console.log(`文件已存在，跳过: ${fileName}`);
        urlToPathMap[url] = `/images/${fileName}`;
        continue;
      }
      
      await downloadFile(url, filePath);
      urlToPathMap[url] = `/images/${fileName}`;
    } catch (error) {
      console.error(`下载失败 ${url}:`, error.message);
    }
  }
  
  // 添加排除的URL到映射中（保持原始URL）
  for (const url of excludeUrls) {
    urlToPathMap[url] = url;
  }
  
  // 保存URL到路径的映射到文件
  const mapFilePath = path.join(__dirname, 'url-to-path-map.json');
  fs.writeFileSync(mapFilePath, JSON.stringify(urlToPathMap, null, 2));
  console.log(`URL映射已保存到: ${mapFilePath}`);
  
  console.log('所有资源下载完成!');
}

processUrls();